import {
  DRACOLoader
} from "three/examples/jsm/loaders/DRACOLoader"; //解密压缩
import {
  GLTFLoader
} from "three/examples/jsm/loaders/GLTFLoader";
import config from "@/config/index.js";
import * as THREE from "three";

const loadGltf = (modelOPtions, progress, loadCallBack) => {
  let lm = new Promise((resolve, reject) => {
    const loader = new GLTFLoader();
    const dracoLoader = new DRACOLoader();
    dracoLoader.setDecoderPath("model/draco/"); //加载draco算法，这样才能解析压缩后的gltf模型格式，具体的draco算法文件，直接可以three依赖文件中找到，赋值到static目录下面就好了
    loader.setDRACOLoader(dracoLoader);
    loader.load(
      modelOPtions.modelUrl,
      (gltf) => {
        resolve(gltf); //返回加载成功的模型
      },
      progress,
      function (e) {
        console.log("加载出错", e);
        reject(e);
      }
    );
  });
  lm.then((obj) => {
    if (loadCallBack) loadCallBack(obj);
  });
}

export const loadUtilsGltf = (modelUrl) => {
  //利用Promise加载模型
  let lm = new Promise((resolve, reject) => {
    let loader = new GLTFLoader();
    let dracoLoader = new DRACOLoader();
    dracoLoader.setDecoderPath("model/draco/"); //加载draco算法，这样才能解析压缩后的gltf模型格式，具体的draco算法文件，直接可以three依赖文件中找到，赋值到static目录下面就好了
    loader.setDRACOLoader(dracoLoader);
    loader.load(
      modelUrl,
      (gltf) => {
        resolve(gltf); //返回加载成功的模型
      },
      undefined,
      function (e) {
        console.log("加载出错", e);
        reject(e);
      }
    );
  });
  return lm.then((obj) => {
    // console.log("模型：", obj);
    return obj.scene;
  });
}

export const loadAllGltfPoint = async (group, points, loadCallBack, options = {
  scale: 2
}) => {
  const cameraGltf = await loadUtilsGltf(config.publicPath + "/model/gltf/camera.gltf");
  // console.log(cameraGltf);
  points.forEach(val => {
    const currentCamera = cameraGltf.children[val.type];
    const cameraGltfClone = addGltfModelPoint(val, currentCamera, options);
    group.add(cameraGltfClone);
  })
  if (loadCallBack) loadCallBack(cameraGltf)
}

export const addGltfModelPoint = (val, currentCamera, options = { scale: 2, name: undefined, offsetY: 0 }) => {
  const cameraGltfClone = currentCamera.clone();
  
  // 克隆材质
  cameraGltfClone.geometry = currentCamera.geometry.clone();
  cameraGltfClone.material = currentCamera.material.clone();
  
  cameraGltfClone.name = options.name || val.name;
  //中心点计算
  cameraGltfClone.geometry.computeBoundingBox();
  cameraGltfClone.geometry.center()
  // 调整大小与位置
  cameraGltfClone.scale.set(options.scale, options.scale, options.scale);
  cameraGltfClone.rotation.set(0, THREE.MathUtils.degToRad(60), 0);
  cameraGltfClone.position.set(val.position.x, val.position.y + (options.offsetY || 0), val.position.z);

  cameraGltfClone.userData.data = val;
  // console.log(cameraGltfClone)
  return cameraGltfClone;
}

export default loadGltf;